﻿using Aspose.Cells;
using HDSmartCommunity.Models;
using NPOI.SS.UserModel;
using NPOI.Util;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace HDSmartCommunity.BUS
{
    public class LogBUS
    {
        public ResponseMessage DownLoad()
        {
            ResponseMessage message = new ResponseMessage();
            List<LogInfo> list = new List<LogInfo>();
            string logPath = AppDomain.CurrentDomain.BaseDirectory + "/wwwroot/Log";
            if (Directory.Exists(logPath))
            {
                DirectoryInfo folder_base = new DirectoryInfo(logPath);
                FileInfo[] files_base = folder_base.GetFiles("*.txt");  //获取.txt文件
                foreach (var file_txt in files_base)
                {
                    LogInfo logInfo = new LogInfo();
                    //获取文件创建时间
                    logInfo.FileName = file_txt.Name;
                    logInfo.FilePath = "/Log/" + file_txt.Name;
                    list.Add(logInfo);
                }
            }
            message.total = list.Count();
            message.data = list;
            return message;
        }

        public ResponseMessage PZDownLoad(string starttime, string endtime, string numberno)
        {
            DateTime dt_start = Convert.ToDateTime(starttime).Date;
            DateTime dt_end = Convert.ToDateTime(endtime).Date;
            ResponseMessage message = new ResponseMessage();
            List<LogInfo> list = new List<LogInfo>();
            string logPath = AppDomain.CurrentDomain.BaseDirectory + "wwwroot/Log/" + numberno;
            if (Directory.Exists(logPath))
            {
                DirectoryInfo folder_base = new DirectoryInfo(logPath);
                FileInfo[] files_base = folder_base.GetFiles("*.txt");  //获取.txt文件
                foreach (var file_txt in files_base)
                {
                    DateTime filetime = file_txt.CreationTime.Date;
                    if (filetime >= dt_start && filetime <= dt_end)
                    {
                        LogInfo logInfo = new LogInfo();
                        //获取文件创建时间
                        logInfo.FileName = file_txt.Name;
                        logInfo.FilePath = "/Log/" + numberno + "/" + file_txt.Name;
                        list.Add(logInfo);
                    }
                }
            }
            message.total = list.Count();
            message.data = list;
            return message;
        }

        public ResponseMessage NetworkDownLoad()
        {
            ResponseMessage message = new ResponseMessage();
            List<LogInfo> list = new List<LogInfo>();
            string logPath = AppDomain.CurrentDomain.BaseDirectory + "/wwwroot/TestLog/Network";
            if (Directory.Exists(logPath))
            {
                DirectoryInfo folder_base = new DirectoryInfo(logPath);
                FileInfo[] files_base = folder_base.GetFiles("*.txt");  //获取.txt文件
                foreach (var file_txt in files_base)
                {
                    LogInfo logInfo = new LogInfo();
                    //获取文件创建时间
                    logInfo.FileName = file_txt.Name;
                    logInfo.FilePath = "/TestLog/Network/" + file_txt.Name;
                    list.Add(logInfo);
                }
            }
            message.total = list.Count();
            message.data = list;
            return message;
        }

        public ResponseMessage SerialDownLoad()
        {
            ResponseMessage message = new ResponseMessage();
            List<LogInfo> list = new List<LogInfo>();
            string logPath = AppDomain.CurrentDomain.BaseDirectory + "/wwwroot/TestLog/Serial";
            if (Directory.Exists(logPath))
            {
                DirectoryInfo folder_base = new DirectoryInfo(logPath);
                FileInfo[] files_base = folder_base.GetFiles("*.txt");  //获取.txt文件
                foreach (var file_txt in files_base)
                {
                    LogInfo logInfo = new LogInfo();
                    //获取文件创建时间
                    logInfo.FileName = file_txt.Name;
                    logInfo.FilePath = "/TestLog/Serial/" + file_txt.Name;
                    list.Add(logInfo);
                }
            }
            message.total = list.Count();
            message.data = list;
            return message;
        }

        public ResponseMessage KoneVoltageDownLoad(string starttime, string endtime, string devicename, string type)
        {
            DateTime dt_start = Convert.ToDateTime(starttime).Date;
            DateTime dt_end = Convert.ToDateTime(endtime).Date;
            ResponseMessage message = new ResponseMessage();
            List<LogInfo> list = new List<LogInfo>();
            string logPath = string.Empty;
            if (type == "充电")
            {
                logPath = AppDomain.CurrentDomain.BaseDirectory + "wwwroot/TestData/Charge/" + devicename;
            }
            else
            {
                logPath = AppDomain.CurrentDomain.BaseDirectory + "wwwroot/TestData/DisCharge/" + devicename;
            }
            if (Directory.Exists(logPath))
            {
                DirectoryInfo folder_base = new DirectoryInfo(logPath);
                FileInfo[] files_base = folder_base.GetFiles("*.csv");  //获取.txt文件
                foreach (var file_txt in files_base)
                {
                    DateTime filetime = file_txt.CreationTime.Date;
                    if (filetime >= dt_start && filetime <= dt_end)
                    {
                        LogInfo logInfo = new LogInfo();
                        //获取文件创建时间
                        logInfo.FileName = file_txt.Name;
                        if (type == "充电")
                        {
                            logInfo.FilePath = "/TestData/Charge/" + devicename + "/" + file_txt.Name;
                        }
                        else
                        {
                            logInfo.FilePath = "/TestData/DisCharge/" + devicename + "/" + file_txt.Name;
                        }
                        list.Add(logInfo);
                    }
                }
            }
            message.total = list.Count();
            message.data = list;
            return message;
        }

        public ResponseMessage KoneVoltageData(string starttime, string endtime, string devicename)
        {
            ResponseMessage message = new ResponseMessage();
            string[] charge_path = GetFile(starttime, endtime, devicename, "充电");
            string new_charge_path = MergeData(charge_path);
            DataTable dataTable = ImportCompareMeanExcel(new_charge_path, 0);
            List<KoneBatteryCharge> charge_list = dataTable.AsEnumerable().Select(row =>
           {
               KoneBatteryCharge obj = new KoneBatteryCharge();
               obj.ChargeStartTime = Convert.ToDateTime(row.Field<string>("Column4") == "ChargeStartTime" ? "1970-01-01" : row.Field<string>("Column4"));
               obj.BatteryVoltage = row.Field<string>("Column6");
               obj.FaultCode = row.Field<string>("Column8");
               obj.CreateDateTime = Convert.ToDateTime(row.Field<string>("Column9") == "CreateDateTime" ? "1970-01-01" : row.Field<string>("Column9"));
               return obj;
           }).ToList();

            charge_list.RemoveAll(x => x.ChargeStartTime.Year == 1970 || x.CreateDateTime.Year == 1970);
            List<KoneBatteryCharge> koneBatteryCharges_new = (List<KoneBatteryCharge>)charge_list.OrderBy(x => x.ChargeStartTime).ToList();

            string[] discharge_path = GetFile(starttime, endtime, devicename, "放电");
            string new_discharge_path = MergeData(discharge_path);
            DataTable dis_dataTable = ImportCompareMeanExcel(new_discharge_path, 0);
            List<KoneBatteryDisCharge> discharge_list = dis_dataTable.AsEnumerable().Select(row =>
            {
                KoneBatteryDisCharge obj = new KoneBatteryDisCharge();
                obj.DisChargeStartTime = Convert.ToDateTime(row.Field<string>("Column4") == "DisChargeStartTime" ? "1970-01-01" : row.Field<string>("Column4"));
                obj.BatteryVoltage = row.Field<string>("Column6");
                obj.FaultCode = row.Field<string>("Column8");
                obj.CreateDateTime = Convert.ToDateTime(row.Field<string>("Column9") == "CreateDateTime" ? "1970-01-01" : row.Field<string>("Column9"));
                return obj;
            }).ToList();

            discharge_list.RemoveAll(x => x.DisChargeStartTime.Year == 1970 || x.CreateDateTime.Year == 1970);
            List<KoneBatteryDisCharge> koneBatteryDisCharges_new = (List<KoneBatteryDisCharge>)discharge_list.OrderBy(x => x.DisChargeStartTime).ToList();

            int number = 1;
            string time = DateTime.Now.ToString("yyyyMMddHHmmssfff");
            while (koneBatteryCharges_new.Count > 0)
            {
                if (koneBatteryDisCharges_new.Count > 0)
                {
                    DateTime chargetime = koneBatteryCharges_new[0].ChargeStartTime;
                    DateTime dischargetime = koneBatteryDisCharges_new[0].DisChargeStartTime;
                    double dy_start = Convert.ToDouble(koneBatteryDisCharges_new[0].BatteryVoltage);
                    int last_index = koneBatteryDisCharges_new.FindLastIndex(x => x.DisChargeStartTime == dischargetime);
                    double dy_end = Convert.ToDouble(koneBatteryDisCharges_new[last_index].BatteryVoltage);
                    string fault = string.Empty; ;
                    int fault_index = koneBatteryDisCharges_new.FindLastIndex(x => x.DisChargeStartTime == dischargetime && x.FaultCode != "0");
                    if (fault_index > -1)
                    {
                        fault = koneBatteryDisCharges_new[fault_index].FaultCode;
                    }
                    int fault_charge_index = koneBatteryCharges_new.FindLastIndex(x => x.ChargeStartTime ==chargetime && x.FaultCode != "0");
                    if (fault_charge_index > -1)
                    {
                        fault = koneBatteryCharges_new[fault_charge_index].FaultCode;
                    }
                    InsertExcelData(chargetime.ToString("yyyy-MM-dd HH:mm:ss"), dischargetime.ToString("yyyy-MM-dd HH:mm:ss"), dy_start,dy_end,fault,number, devicename, time);
                    koneBatteryCharges_new.RemoveAll(x => x.ChargeStartTime == chargetime);
                    koneBatteryDisCharges_new.RemoveAll(x => x.DisChargeStartTime == dischargetime);
                    number++;
                }
                else
                {
                    koneBatteryCharges_new.RemoveAll(x => x.ChargeStartTime == koneBatteryCharges_new[0].ChargeStartTime);
                }
            }


            return message;
        }

        public string[] GetFile(string starttime, string endtime, string devicename, string type)
        {
            DateTime dt_start = Convert.ToDateTime(starttime).Date;
            DateTime dt_end = Convert.ToDateTime(endtime).Date;
            ResponseMessage message = new ResponseMessage();
            List<string> list = new List<string>();
            string logPath = string.Empty;
            if (type == "充电")
            {
                logPath = AppDomain.CurrentDomain.BaseDirectory + "wwwroot/TestData/Charge/" + devicename;
            }
            else
            {
                logPath = AppDomain.CurrentDomain.BaseDirectory + "wwwroot/TestData/DisCharge/" + devicename;
            }
            if (Directory.Exists(logPath))
            {
                DirectoryInfo folder_base = new DirectoryInfo(logPath);
                FileInfo[] files_base = folder_base.GetFiles("*.csv");  //获取.txt文件
                foreach (var file_txt in files_base)
                {
                    DateTime filetime = file_txt.CreationTime.Date;
                    if (filetime >= dt_start && filetime <= dt_end)
                    {
                        string FilePath = string.Empty;
                        //获取文件创建时间
                        if (type == "充电")
                        {
                            FilePath = AppDomain.CurrentDomain.BaseDirectory + "wwwroot/TestData/Charge/" + devicename + "/" + file_txt.Name;
                        }
                        else
                        {
                            FilePath = AppDomain.CurrentDomain.BaseDirectory + "wwwroot/TestData/DisCharge/" + devicename + "/" + file_txt.Name;
                        }
                        list.Add(FilePath);
                    }
                }
            }

            return list.ToArray();
        }

        public string MergeData(string[] sourceFiles)
        {
            string path = string.Empty;
            try
            {
                string outputFile = AppDomain.CurrentDomain.BaseDirectory + "merged.csv"; // 输出文件
                StringBuilder sb = new StringBuilder();

                foreach (string file in sourceFiles)
                {
                    sb.Append(File.ReadAllText(file)); // 读取文件内容并追加到StringBuilder中
                    //sb.AppendLine(); // 在文件之间添加空行（可选）
                }

                File.WriteAllText(outputFile, sb.ToString()); // 将StringBuilder的内容写入到输出文件
                path = outputFile;
            }
            catch (Exception ex)
            {

            }
            return path;
        }

        public DataTable ImportCompareMeanExcel(string strFilePath, int sheet_index)
        {
            Workbook workbook = new Workbook(strFilePath);
            DataTable dtExcel = null;
            try
            {
                Cells cells = workbook.Worksheets[sheet_index].Cells;
                dtExcel = cells.ExportDataTableAsString(0, 0, cells.MaxDataRow + 1, cells.MaxColumn + 1, false);//showTitle
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
            return dtExcel;
        }

        public bool InsertExcelData(string ChargeStartTime, string DisChargeStartTime, double Voltage_Start, double Voltage_End, string fault, int no, string devicename,string random)
        {
            try
            {
                string path = AppDomain.CurrentDomain.BaseDirectory;
                string dirpath = string.Empty;

                dirpath = AppDomain.CurrentDomain.BaseDirectory + @"wwwroot/TestData/Import";

                string filepath = dirpath + @"/" + devicename + "_" + random + ".csv";
                //LogHelper.Log(filepath);
                //生成目录
                //创建文件夹
                if (Directory.Exists(dirpath) == false)//如果不存在就创建file文件夹
                {
                    Directory.CreateDirectory(dirpath);
                }

                // 判断文件是否存在，不存在则创建，否则读取值显示到txt文档
                if (!System.IO.File.Exists(filepath))
                {
                    FileStream fs1 = new FileStream(filepath, FileMode.Create, FileAccess.Write);//创建写入文件 

                    fs1.Close();

                    File.AppendAllText(filepath, "序号,充电开始时间,逆变开始时间,逆变开始电池电压,逆变结束电压,故障号" + "\r\n");
                    File.AppendAllText(filepath, string.Format("{0},{1},{2},{3},{4},{5}", no, ChargeStartTime, DisChargeStartTime, Math.Round(Voltage_Start, 2), Math.Round(Voltage_End, 2), fault) + "\r\n");

                }
                else
                {
                    File.AppendAllText(filepath, string.Format("{0},{1},{2},{3},{4},{5}", no, ChargeStartTime, DisChargeStartTime, Math.Round(Voltage_Start, 2), Math.Round(Voltage_End, 2), fault) + "\r\n");
                }
            }
            catch (Exception ex)
            {
                DataSaveLogHelper.Log(ex.ToString());
            }
            return true;
        }

    }
}
